package com.dkh.recommend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dkh.recommend.dto.BlogCommentDTO;
import com.dkh.recommend.dto.CommentDTO;
import com.dkh.recommend.dto.Result;
import com.dkh.recommend.dto.UserDTO;
import com.dkh.recommend.entity.TbComment;
import com.dkh.recommend.entity.TbRelate;
import com.dkh.recommend.entity.TbUser;
import com.dkh.recommend.service.ITbUserService;
import com.dkh.recommend.service.TbBlogCommentService;
import com.dkh.recommend.entity.TbBlogComment;
import com.dkh.recommend.mapper.TbBlogCommentMapper;
import com.dkh.recommend.utils.RecScoreUtils;
import com.dkh.recommend.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.dkh.recommend.utils.RedisConstants.BLOG_COMMENT_LIKE_KEY;
import static com.dkh.recommend.utils.RedisConstants.COMMENT_LIKE_KEY;

/**
* @author DENG
* @description 针对表【tb_blog_comment】的数据库操作Service实现
* @createDate 2023-04-24 18:36:32
*/
@Service
public class TbBlogCommentServiceImpl extends ServiceImpl<TbBlogCommentMapper, TbBlogComment>
    implements TbBlogCommentService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private TbBlogCommentMapper blogCommentMapper;

    @Autowired
    private ITbUserService userService;


    //    对音乐故事评论
    @Override
    @Transactional
    public Result addComment(TbBlogComment comment) {
//        获取登录用户的id
        Long userId = UserHolder.getUser().getUserId();
        comment.setUserId(userId);
        long timeMillis = System.currentTimeMillis();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String addTime = simpleDateFormat.format(timeMillis);
        comment.setAddTime(addTime);
        boolean issave = this.save(comment);
        if (issave){
            return Result.ok();
        }
        return Result.fail("评论失败请重试！");
    }

    /**
     * 查看我的音乐故事评论
     * @return
     */
    @Override
    public Result myBlogComment() {
//        获取登录用户的id
        Long userId = UserHolder.getUser().getUserId();
//          从数据库查询我的评论
        LambdaQueryWrapper<TbBlogComment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbBlogComment::getUserId,userId);
        List<TbBlogComment> blogCommentList = this.list(queryWrapper);
        return Result.ok(blogCommentList);
    }

    /**
     * 删除用户的评论
     * @param commentId
     * @return
     */
    @Override
    public Result deleteComment(String commentId) {
        //        获取登录用户的id
        Long userId = UserHolder.getUser().getUserId();
        Long commentIdL = Long.valueOf(commentId);
        LambdaQueryWrapper<TbBlogComment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbBlogComment::getCommentId,commentIdL)
                .eq(TbBlogComment::getUserId,userId);

//        删除评论
        boolean isremove = this.remove(queryWrapper);
        if (isremove){
//            删除评论成功
            return Result.ok();
        }
        return Result.fail("删除评论失败请重试！！");


    }

    /**
     * 该用户是否对该评论点赞了
     * @param commentId
     * @return
     */
    @Override
    public Result orNotLike(String commentId) {
        Boolean like = isLike(commentId);
        return Result.ok(like);
    }

    private Boolean isLike(String commentId){
        UserDTO user = UserHolder.getUser();
//        如果未登录则不需要查询是否点赞
        if (user == null || user.toString().isEmpty()){
            return null ;
        }
        Long userId = user.getUserId();
//        判断当前登录用户是否已经点赞
        String key = BLOG_COMMENT_LIKE_KEY + commentId;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());

        return (score != null);
    }

    /**
     * 点赞
     * @param commentId
     * @return
     */
    @Override
    public Result likeComment(String commentId) {
//        1.获取用户Id
        Long userId = UserHolder.getUser().getUserId();
        Long commentIdL = Long.valueOf(commentId);
        String msg = "操作成功";
        if (UserHolder.getUser().toString().isEmpty()||UserHolder.getUser().toString().equals("")){
//            用户未登陆请先登陆
            return Result.fail("请先登陆");
        }
//        //        2.判断当前登录用户是否已经点赞
        String key = BLOG_COMMENT_LIKE_KEY  + commentId;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score == null){

            Boolean isSucess = blogCommentMapper.addCountLike(commentIdL);

            // 3.2.保存用户到Redis的set集合  zadd key value score
            if (isSucess){
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
                msg = "点赞成功";
            }else {
                return Result.fail("点赞失败");
            }

        }else {
            // 4.如果已点赞，取消点赞
            // 4.1.数据库点赞数 -1
            blogCommentMapper.reduceCountLike(commentIdL);
            // 4.2.把用户从Redis的set集合移除
            stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            msg = "取消点赞成功";
        }
        return Result.ok(msg);
    }



    //    根据音乐故事id获取到评论列表放入CommentDTO返回前端
    @Override
    public Result getCommentByBlogId(String blogId) {
        Long blogIdL = Long.valueOf(blogId);

//        UserDTO
//        根据blogId查找blogComment
        LambdaQueryWrapper<TbBlogComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbBlogComment::getBlogId,blogIdL).orderByDesc(TbBlogComment::getCountLike).orderByDesc(TbBlogComment::getBlogId);
        List<TbBlogComment> blogCommentList = this.list(wrapper);
        List<Long> Ids = new ArrayList<>();
//        收集用户ids
        blogCommentList.stream().forEach(comment -> {
            Long userId = comment.getUserId();
            Ids.add(userId);

        });

//        查询用户列表获取名字
        if (Ids.isEmpty() || Ids.size() <= 0){
//            没有评论返回空
            return Result.ok();
        }
        List<TbUser> userList = userService.listByIds(Ids);
        //        key: UserId  value:UserName
        Map<Long,String> nameMap = new HashMap<>();
//        一key:UserId  value:UserIcon
        Map<Long,String> iconMap = new HashMap<>();
        userList.stream().forEach(user -> {
            nameMap.put(user.getUserId(),user.getUserName());
            iconMap.put(user.getUserId(),user.getUserIcon());
        });

        List<BlogCommentDTO> blogCommentDTOList = new ArrayList<>();
        blogCommentList.stream().forEach(comment -> {
            BlogCommentDTO commentDTO = BeanUtil.toBean(comment, BlogCommentDTO.class);
//            根据userId取出UserName并放入commentDTO
            commentDTO.setUserName(nameMap.get(comment.getUserId()));
            commentDTO.setUserIcon(iconMap.get(comment.getUserId()));
            blogCommentDTOList.add(commentDTO);
        });

        return Result.ok(blogCommentDTOList);
    }



}




